package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService sdService;

    /**
     * 新增套餐
     * @param setmealDto
     */
    @Override
    public void add(SetmealDto setmealDto) {
        //1. 添加套餐信息入库
        this.save(setmealDto);

        //2. 处理套餐对应的菜品关系数据
        Long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
            return setmealDish;
        }).collect(Collectors.toList());

        //3. 将套餐菜品关系数据入库
        sdService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐及套餐关联的菜品关系
     * @param ids
     */
    @Override
    public void removeWithDish( List<Long> ids) {
        //根据id删除套餐
        this.removeByIds(ids);

        //删除套餐关联的菜品关系
        ids.stream().forEach(setmealId->{
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId,setmealId);
            sdService.remove(wrapper);
        });
    }
}
